// 加载API列表
function loadApiList(page = 1) {
    currentPage = page;
    
    const searchQuery = $('#search-input').val();
    
    $.ajax({
        url: '/api/data',
        method: 'GET',
        data: {
            search: searchQuery,
            page: page,
            per_page: perPage
        },
        success: function(response) {
            renderApiList(response.apis);
            renderPagination(response.pagination);
        },
        error: function(error) {
            console.error('加载API列表失败:', error);
            showToast('error', '加载API列表失败');
        }
    });
}

// 渲染API列表
function renderApiList(apis) {
    const apiList = $('#api-list');
    apiList.empty();
    
    if (apis.length === 0) {
        apiList.append('<tr><td colspan="6" class="text-center">暂无数据</td></tr>');
        return;
    }
    
    apis.forEach(api => {
        const tags = api.tags && api.tags.length > 0
            ? api.tags.map(tag => `<span class="badge bg-info me-1">${tag}</span>`).join('')
            : '';
        
        const methodBadge = getMethodBadge(api.method);
        
        apiList.append(`
            <tr data-id="${api.id}">
                <td>${api.name}</td>
                <td>${methodBadge}</td>
                <td>${api.path}</td>
                <td>${tags}</td>
                <td>${api.updated_at}</td>
                <td>
                    <button class="btn btn-sm btn-info view-api" data-id="${api.id}">
                        <i class="bi bi-eye"></i> 查看
                    </button>
                    <button class="btn btn-sm btn-primary edit-api" data-id="${api.id}">
                        <i class="bi bi-pencil"></i> 编辑
                    </button>
                    <button class="btn btn-sm btn-danger delete-api" data-id="${api.id}">
                        <i class="bi bi-trash"></i> 删除
                    </button>
                </td>
            </tr>
        `);
    });
}

// 获取HTTP方法对应的徽章
function getMethodBadge(method) {
    const badgeClass = {
        'GET': 'bg-success',
        'POST': 'bg-primary',
        'PUT': 'bg-warning',
        'DELETE': 'bg-danger',
        'PATCH': 'bg-info'
    };
    
    return `<span class="badge ${badgeClass[method] || 'bg-secondary'}">${method}</span>`;
}

// 渲染分页
function renderPagination(pagination) {
    const paginationEl = $('#pagination ul');
    paginationEl.empty();
    
    // 更新分页信息
    const start = (pagination.current_page - 1) * pagination.per_page + 1;
    const end = Math.min(pagination.current_page * pagination.per_page, pagination.total_items);
    $('#pagination-info').text(`显示 ${start}-${end} 条，共 ${pagination.total_items} 条`);
    
    // 上一页
    paginationEl.append(`
        <li class="page-item ${pagination.current_page === 1 ? 'disabled' : ''}">
            <a class="page-link" href="#" data-page="${pagination.current_page - 1}">上一页</a>
        </li>
    `);
    
    // 页码
    for (let i = 1; i <= pagination.total_pages; i++) {
        if (
            i === 1 || 
            i === pagination.total_pages || 
            (i >= pagination.current_page - 2 && i <= pagination.current_page + 2)
        ) {
            paginationEl.append(`
                <li class="page-item ${i === pagination.current_page ? 'active' : ''}">
                    <a class="page-link" href="#" data-page="${i}">${i}</a>
                </li>
            `);
        } else if (
            i === pagination.current_page - 3 || 
            i === pagination.current_page + 3
        ) {
            paginationEl.append(`
                <li class="page-item disabled">
                    <a class="page-link" href="#">...</a>
                </li>
            `);
        }
    }
    
    // 下一页
    paginationEl.append(`
        <li class="page-item ${pagination.current_page === pagination.total_pages ? 'disabled' : ''}">
            <a class="page-link" href="#" data-page="${pagination.current_page + 1}">下一页</a>
        </li>
    `);
}

// 查看API详情
function viewApi(apiId) {
    $.ajax({
        url: `/api/${apiId}`,
        method: 'GET',
        success: function(response) {
            if (response.success) {
                const api = response.api;
                
                // 填充模态框
                $('#view-api-name').text(api.name);
                $('#view-api-method').html(getMethodBadge(api.method));
                $('#view-api-path').text(api.path);
                $('#view-api-description').text(api.description || '无描述');
                
                // 标签
                const tagsHtml = api.tags && api.tags.length > 0
                    ? api.tags.map(tag => `<span class="badge bg-info me-1">${tag}</span>`).join('')
                    : '无标签';
                $('#view-api-tags').html(tagsHtml);
                
                // 请求头
                renderJsonViewer('#view-api-headers', api.headers || {});
                
                // 请求参数
                renderJsonViewer('#view-api-params', api.params || {});
                
                // 请求体
                renderJsonViewer('#view-api-body', api.body || {});
                
                // 响应
                renderJsonViewer('#view-api-response', api.response || {});
                
                // 显示模态框
                $('#viewModal').modal('show');
            } else {
                showToast('error', response.message || '获取API详情失败');
            }
        },
        error: function(error) {
            console.error('获取API详情失败:', error);
            showToast('error', '获取API详情失败');
        }
    });
}

// 渲染JSON查看器
function renderJsonViewer(selector, data) {
    $(selector).empty();
    
    if (Object.keys(data).length === 0) {
        $(selector).text('无数据');
        return;
    }
    
    const jsonViewer = new JSONViewer();
    $(selector).append(jsonViewer.getContainer());
    jsonViewer.showJSON(data);
}

// 编辑API
function editApi(apiId) {
    $.ajax({
        url: `/api/${apiId}`,
        method: 'GET',
        success: function(response) {
            if (response.success) {
                const api = response.api;
                
                // 重置表单
                $('#add-edit-form')[0].reset();
                
                // 设置表单模式
                $('#add-edit-form').data('mode', 'edit');
                $('#add-edit-form').data('id', api.id);
                $('#addEditModalLabel').text('编辑API');
                
                // 填充表单
                $('#api-name').val(api.name);
                $('#api-method').val(api.method);
                $('#api-path').val(api.path);
                $('#api-description').val(api.description);
                
                // 标签
                if (api.tags && api.tags.length > 0) {
                    $('#api-tags').val(api.tags.join(','));
                }
                
                // 请求头
                $('#api-headers').val(JSON.stringify(api.headers || {}, null, 2));
                
                // 请求参数
                $('#api-params').val(JSON.stringify(api.params || {}, null, 2));
                
                // 请求体
                $('#api-body').val(JSON.stringify(api.body || {}, null, 2));
                
                // 响应
                $('#api-response').val(JSON.stringify(api.response || {}, null, 2));
                
                // 显示模态框
                $('#addEditModal').modal('show');
            } else {
                showToast('error', response.message || '获取API详情失败');
            }
        },
        error: function(error) {
            console.error('获取API详情失败:', error);
            showToast('error', '获取API详情失败');
        }
    });
}

// 确认删除API
function confirmDeleteApi(apiId, apiName) {
    $('#confirm-delete-btn').data('id', apiId);
    $('#delete-api-name').text(apiName);
    $('#deleteModal').modal('show');
}

// 删除API
function deleteApi(apiId) {
    $.ajax({
        url: `/api/${apiId}`,
        method: 'DELETE',
        success: function(response) {
            if (response.success) {
                showToast('success', response.message || 'API删除成功');
                $('#deleteModal').modal('hide');
                loadApiList(currentPage);
            } else {
                showToast('error', response.message || 'API删除失败');
            }
        },
        error: function(error) {
            console.error('API删除失败:', error);
            showToast('error', 'API删除失败');
        }
    });
}

// 保存API（新增或编辑）
function saveApi() {
    const mode = $('#add-edit-form').data('mode') || 'add';
    const apiId = $('#add-edit-form').data('id');
    
    // 收集表单数据
    const apiData = {
        name: $('#api-name').val(),
        method: $('#api-method').val(),
        path: $('#api-path').val(),
        description: $('#api-description').val(),
        tags: $('#api-tags').val() ? $('#api-tags').val().split(',').map(tag => tag.trim()) : []
    };
    
    // 解析JSON字段
    try {
        apiData.headers = $('#api-headers').val() ? JSON.parse($('#api-headers').val()) : {};
        apiData.params = $('#api-params').val() ? JSON.parse($('#api-params').val()) : {};
        apiData.body = $('#api-body').val() ? JSON.parse($('#api-body').val()) : {};
        apiData.response = $('#api-response').val() ? JSON.parse($('#api-response').val()) : {};
    } catch (e) {
        showToast('error', 'JSON格式错误，请检查');
        return;
    }
    
    // 发送请求
    const url = mode === 'edit' ? `/api/${apiId}` : '/api/';
    const method = mode === 'edit' ? 'PUT' : 'POST';
    
    $.ajax({
        url: url,
        method: method,
        contentType: 'application/json',
        data: JSON.stringify(apiData),
        success: function(response) {
            if (response.success) {
                showToast('success', response.message || 'API保存成功');
                $('#addEditModal').modal('hide');
                loadApiList(currentPage);
            } else {
                showToast('error', response.message || 'API保存失败');
            }
        },
        error: function(error) {
            console.error('API保存失败:', error);
            showToast('error', 'API保存失败');
        }
    });
}

// 导入API
function importApi() {
    const formData = new FormData($('#import-form')[0]);
    
    $.ajax({
        url: '/api/import',
        method: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        success: function(response) {
            if (response.success) {
                showToast('success', response.message || 'API导入成功');
                $('#importModal').modal('hide');
                loadApiList(1);
            } else {
                showToast('error', response.message || 'API导入失败');
            }
        },
        error: function(error) {
            console.error('API导入失败:', error);
            showToast('error', 'API导入失败');
        }
    });
}